<template>
  <view class="container">
    <!-- 顶部状态栏占位 -->
    <view class="status-bar"></view>

    <!-- 支付金额 -->
    <view class="payment-amount-section">
      <text class="payment-label">支付金额</text>
      <text class="payment-amount">¥{{ order.order_price }}</text>
      <text class="order-number">订单编号：{{ order.order_no }}</text>
      <view class="pay-timer">
        <text class="timer-label">支付剩余时间</text>
        <text class="timer-text">{{ countDown }}</text>
      </view>
    </view>

    <!-- 支付方式选择 -->
    <view class="payment-methods-section">
      <view class="section-title">支付方式</view>

      <view
        class="payment-method-item"
        @tap="selectPayMethod('wechat')"
        :class="{ selected: payMethod === 'wechat' }"
      >
        <view class="method-icon wechat-icon">
          <image src="/static/wx_pay.png" mode="aspectFit"></image>
        </view>
        <view class="method-info">
          <text class="method-name">微信支付</text>
          <text class="method-desc">微信安全支付</text>
        </view>
        <view class="method-select">
          <view
            class="select-circle"
            :class="{ active: payMethod === 'wechat' }"
          >
            <view class="select-inner" v-if="payMethod === 'wechat'"></view>
          </view>
        </view>
      </view>

      <view
        class="payment-method-item"
        @tap="selectPayMethod('balance')"
        :class="{ selected: payMethod === 'balance' }"
      >
        <view class="method-icon balance-icon">
          <!-- uniapp钱包图标 -->
          <uni-icons type="wallet" size="24" color="#5C8D69"></uni-icons>
        </view>
        <view class="method-info">
          <text class="method-name">余额支付</text>
          <text class="method-desc">当前余额：¥{{ userBalance.toFixed(2) }}</text>
        </view>
        <view class="method-select">
          <view
            class="select-circle"
            :class="{ active: payMethod === 'balance' }"
          >
            <view class="select-inner" v-if="payMethod === 'balance'"></view>
          </view>
        </view>
      </view>
    </view>

    <!-- 余额不足提示 -->
    <view class="balance-tip" v-if="payMethod === 'balance' && !isBalanceEnough">
      <view class="balance-tip-icon">
        <uni-icons type="info-filled" color="#FF5000" size="16"></uni-icons>
      </view>
      <view class="balance-tip-text">
        <text>余额不足，还差 ¥{{ balanceShortage }}，</text>
        <text class="recharge-link" @tap="goRecharge">去充值</text>
      </view>
    </view>

    <!-- 优惠券使用提示 -->
    <!-- <view class="discount-tip" v-if="discountAmount > 0">
      <view class="discount-icon">
        <image src="/static/payment/discount.png" mode="aspectFit"></image>
      </view>
      <view class="discount-text">
        <text>已使用优惠 ¥{{ discountAmount }}</text>
      </view>
    </view> -->

    <!-- 底部支付按钮 -->
    <view class="footer">
      <button class="pay-btn" @tap="confirmPayment" :disabled="payMethod === 'balance' && !isBalanceEnough">
        <text class="pay-btn-text">立即支付</text>
        <text class="pay-btn-amount">¥{{ order.order_price }}</text>
      </button>
    </view>

    <!-- 支付成功弹窗 -->
    <view class="success-modal" v-if="showSuccessModal">
      <view class="modal-mask"></view>
      <view class="success-content">
        <view class="success-icon">
          <image src="/static/payment/success.png" mode="aspectFit"></image>
        </view>
        <text class="success-title">支付成功</text>
        <text class="success-desc">感谢您的购买，祝您禅意生活</text>
        <view class="success-btns">
          <button class="success-btn order-btn" @tap="viewOrder">
            查看订单
          </button>
          <button class="success-btn home-btn" @tap="goHome">返回首页</button>
        </view>
      </view>
    </view>
    <!-- 支付确认弹窗 -->
    <view class="confirm-modal" v-if="showConfirmModal">
      <view class="modal-mask" @tap="closeConfirmModal"></view>
      <view class="confirm-content">
        <text class="confirm-title">确认支付</text>
        <text class="confirm-amount">¥{{ order.order_price }}</text>
        <text class="confirm-method" v-if="payMethod === 'wechat'">微信支付</text>
        <text class="confirm-method" v-if="payMethod === 'balance'">余额支付</text>

        <view class="confirm-tips">
          <text>请确认金额无误后进行支付</text>
        </view>
        <view class="confirm-btns">
          <button class="confirm-btn cancel-btn" @tap="closeConfirmModal">
            取消
          </button>
          <button class="confirm-btn proceed-btn" @tap="processPay">
            确认支付
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { cancelOrderApi, orderDetailApi, payOrderApi, payStatusApi } from "../../api/order";
import { getInfo } from "../../api/user";
import { goto, hideloading, tip } from "../../utils";

export default {
  data() {
    return {
      orderId: 0,
      payMethod: "wechat", // 默认选择微信支付
      countdown: 0, // 15分钟倒计时（秒）
      timer: null,
      showSuccessModal: false,
      showConfirmModal: false,
      order: {},
      userBalance: 0, // 用户余额
    };
  },
  computed: {
    // 格式化倒计时
    countDown() {
      const hours = Math.floor(this.countdown / 3600);
      const minutes = Math.floor((this.countdown - hours * 3600) / 60);
      const seconds = this.countdown % 60;
      return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(
        2,
        "0"
      )}:${String(seconds).padStart(2, "0")}`;
    },
    
    // 余额是否足够支付
    isBalanceEnough() {
      return this.userBalance >= (this.order.order_price || 0);
    },
    
    // 余额不足金额
    balanceShortage() {
      return ((this.order.order_price || 0) - this.userBalance).toFixed(2);
    }
  },
  onLoad(options) {
    // 获取传递过来的订单ID和金额
    if (options.orderId) {
      this.orderId = options.orderId;
    }
    
    // 获取用户信息和余额
    this.getUserInfo();
    
    orderDetailApi({
      order_id: this.orderId,
    }).then((res) => {
      this.order = res.order;
      if (this.order && this.order.order_status && this.order.order_status.value != 10) {
        return uni.showToast({
          title: "订单状态错误",
          icon: "none",
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          },
        });
      } else if (this.order && this.order.pay_status && this.order.pay_status.value != 10) {
        return uni.showToast({
          title: "订单已支付，请勿重复支付",
          icon: "none",
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          },
        });
      }
      this.countdown = res.order.pay_end_count;
      // 启动倒计时
      this.startCountdown();
    });
  },
  onShow() {
    // 页面显示时重新获取用户余额，以便在充值后返回能显示最新余额
    this.getUserInfo();
  },
  onUnload() {
    // 清除倒计时
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 获取用户信息和余额
    getUserInfo() {
      getInfo().then(res => {
        if (res && res.userInfo) {
          this.userBalance = parseFloat(res.userInfo.balance || 0);
        }
      }).catch(err => {
        console.error('获取用户信息失败:', err);
        this.userBalance = 0;
      });
    },
    
    // 前往充值页面
    goRecharge() {
      uni.navigateTo({
        url: '/pages/my/recharge'
      });
    },
    
    // 返回上一页
    navigateBack() {
      uni.showModal({
        title: "提示",
        content: "订单尚未支付，是否放弃支付？",
        confirmColor: "#5C8D69",
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack();
          }
        },
      });
    },

    // 选择支付方式
    selectPayMethod(method) {
      this.payMethod = method;
      // 检查余额支付是否足够
      if (method === "balance" && !this.isBalanceEnough) {
        uni.showToast({
          title: `余额不足，还差${this.balanceShortage}元，可以选择充值`,
          icon: "none",
          duration: 2000
        });
      }
    },

    // 启动倒计时
    startCountdown() {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
		  payStatusApi(this.orderId).then((res)=>{
			  if(res==20){	//已支付
				clearInterval(this.timer);
				this.showSuccessModal = true;
				tip("支付成功",()=>{
					goto("pages/my/order",'redirect')
				})
			  }
		  }).catch(()=>{
			  tip("订单状态错误")
			  clearInterval(this.timer);
		  })
        } else {
          // 时间到，清除定时器
          clearInterval(this.timer);
          cancelOrderApi({
            order_id: this.orderId,
          }).then((res) => {
            // 提示用户订单已超时
            uni.showModal({
              title: "订单超时",
              content: "支付已超时，请重新下单",
              showCancel: false,
              confirmColor: "#5C8D69",
              success: () => {
                uni.navigateBack({
                  delta: 2, // 返回两级页面（返回到商品列表）
                });
              },
            });
          });
        }
      }, 1000);
    },

    // 确认支付
    confirmPayment() {
      if (!this.payMethod) {
        return uni.showToast({
          title: "请选择支付方式",
          icon: "none",
        });
      }
      
      // 检查余额是否足够
      if (this.payMethod === "balance" && !this.isBalanceEnough) {
        return uni.showToast({
          title: `余额不足，还差${this.balanceShortage}元，请充值或选择其他支付方式`,
          icon: "none",
        });
      }

      // 显示支付确认弹窗
      this.showConfirmModal = true;
    },

    // 关闭确认弹窗
    closeConfirmModal() {
      this.showConfirmModal = false;
    },

    // 处理支付逻辑
    processPay() {
      // 关闭确认弹窗
      this.showConfirmModal = false;

      // 显示加载中
      uni.showLoading({
        title: "支付处理中...",
      });

      // 根据支付方式处理不同的支付逻辑
      if (this.payMethod === 'balance') {
        // 余额支付
        payOrderApi({
          order_id: this.orderId,
          use_balance: 1,           // 使用余额支付
          pay_source: 'balance'     // 支付来源为余额
        }).then((res) => {
          console.log('支付结果:', res);
          hideloading();
          
          // 如果返回了支付参数，说明余额不足，需要继续使用微信支付剩余部分
          if (res.payment && Object.keys(res.payment).length > 0) {
            const useBalanceAmount = parseFloat(res.use_balance || 0).toFixed(2);
            
            uni.showToast({
              title: `已使用余额${useBalanceAmount}元，需支付剩余金额`,
              icon: "none",
              duration: 2000
            });
            
            // 发起微信支付
            const self = this;
            uni.requestPayment({
              provider: "wxpay",
              ...res.payment,
              success: function (payRes) {
                hideloading();
                self.showSuccessModal = true;
                tip("支付成功");
                self.getUserInfo(); // 更新用户余额
              },
              fail: function (err) {
                hideloading();
                tip("支付失败：" + JSON.stringify(err));
              }
            });
          } else {
            // 余额足够，直接显示支付成功
            this.showSuccessModal = true;
            tip("余额支付成功");
            this.getUserInfo(); // 更新用户余额
          }
        }).catch(err => {
          hideloading();
          tip("支付失败：" + (err.message || JSON.stringify(err)));
        });
      } else {
        // 微信支付
        payOrderApi({
          order_id: this.orderId,
          use_balance: 0,           // 不使用余额
          pay_source: 'wx'          // 支付来源为微信
        }).then((res) => {
          //发起支付
          const self = this;  // 保存this引用
          uni.requestPayment({
            provider: "wxpay",
            ...res.payment,
            success: function (res) {
              hideloading();
              self.showSuccessModal = true;  // 使用self代替this
              tip("支付成功");
            },
            fail: function (err) {
              hideloading();
              tip("支付失败："+JSON.stringify(err));
            }
          });
        }).catch(err => {
          hideloading();
          tip("支付失败：" + (err.message || JSON.stringify(err)));
        });
      }
    },
    
    // 查看订单
    viewOrder() {
      // 这里跳转到订单详情页
        uni.redirectTo({
        url: `/pages/order/detail?id=${this.orderId}`,
      });
    },

    // 返回首页
    goHome() {
      // 关闭所有页面，打开首页
      uni.switchTab({
        url: "/pages/index/index",
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f5f2ea;
  font-family: "思源宋体", serif;
}

.container {
  width: 100%;
  padding-bottom: 150rpx;
}

.status-bar {
  height: var(--status-bar-height);
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #f5f2ea;
}

.header-left {
  width: 60rpx;
}

.placeholder {
  width: 60rpx;
}

.title-text {
  font-family: "汉仪尚巍手书", "思源宋体", serif;
  font-size: 34rpx;
  color: #6a4c29;
}

.icon-fanhui:before {
  content: "\e8b5";
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #6a4c29;
}

/* 支付金额区域 */
.payment-amount-section {
  margin: 20rpx 30rpx 40rpx;
  background-color: #fff;
  border-radius: 15rpx;
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 5rpx 15rpx rgba(106, 76, 41, 0.05);
  position: relative;
  overflow: hidden;

  &:before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 6rpx;
    background: linear-gradient(90deg, #c8a675, #6a4c29);
  }
}

.payment-label {
  font-size: 28rpx;
  color: #6a4c29;
  margin-bottom: 20rpx;
}

.payment-amount {
  font-size: 60rpx;
  color: #6a4c29;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.order-number {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.pay-timer {
  background-color: #f8f5ef;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
}

.timer-label {
  font-size: 24rpx;
  color: #6a4c29;
  margin-right: 10rpx;
}

.timer-text {
  font-size: 24rpx;
  color: #ff5000;
  font-weight: bold;
}

/* 支付方式区域 */
.payment-methods-section {
  margin: 20rpx 30rpx;
  background-color: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 5rpx 15rpx rgba(106, 76, 41, 0.05);
}

.section-title {
  font-size: 30rpx;
  color: #6a4c29;
  font-weight: 500;
  margin-bottom: 30rpx;
  font-family: "汉仪尚巍手书", "思源宋体", serif;
}

.payment-method-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid rgba(106, 76, 41, 0.05);
  transition: all 0.3s;

  &:last-child {
    border-bottom: none;
  }

  &.selected {
    background-color: rgba(200, 166, 117, 0.05);
  }
}

.method-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 15rpx;
  overflow: hidden;
  margin-right: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;

  image {
    width: 60rpx;
    height: 60rpx;
  }
}

.wechat-icon {
  background-color: rgba(9, 187, 7, 0.1);
}

.balance-icon {
  background-color: rgba(200, 166, 117, 0.1);
}

.method-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.method-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 5rpx;
}

.method-desc {
  font-size: 24rpx;
  color: #999;
}

.method-select {
  padding: 0 10rpx;
}

.select-circle {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  justify-content: center;
  align-items: center;

  &.active {
    border-color: #c8a675;
  }
}

.select-inner {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #c8a675;
}

/* 优惠提示 */
.discount-tip {
  margin: 20rpx 30rpx;
  display: flex;
  align-items: center;
}

.discount-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;

  image {
    width: 100%;
    height: 100%;
  }
}

.discount-text {
  font-size: 24rpx;
  color: #c8a675;
}

/* 余额不足提示 */
.balance-tip {
  margin: 20rpx 30rpx;
  display: flex;
  align-items: center;
  background-color: #FFF8E1;
  padding: 20rpx;
  border-radius: 10rpx;
}

.balance-tip-icon {
  margin-right: 10rpx;
}

.balance-tip-text {
  font-size: 24rpx;
  color: #FF5000;
}

.recharge-link {
  color: #6a4c29;
  text-decoration: underline;
}

/* 底部支付按钮 */
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -5rpx 15rpx rgba(106, 76, 41, 0.05);
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.pay-btn {
  height: 90rpx;
  background: linear-gradient(135deg, #c8a675 0%, #6a4c29 100%);
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 45rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pay-btn-text {
  margin-right: 20rpx;
}

.pay-btn-amount {
  font-weight: bold;
}

/* 支付成功弹窗 */
.success-modal,
.confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.success-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 50rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 10rpx 30rpx rgba(106, 76, 41, 0.2);
}

.success-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 30rpx;

  image {
    width: 100%;
    height: 100%;
  }
}

.success-title {
  font-size: 36rpx;
  color: #6a4c29;
  font-weight: bold;
  margin-bottom: 20rpx;
  font-family: "汉仪尚巍手书", "思源宋体", serif;
}

.success-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 40rpx;
}

.success-btns {
  display: flex;
  width: 100%;
  gap: 20rpx;
}

.success-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.order-btn {
  background-color: #f1e3c4;
  color: #6a4c29;
  border: 1rpx solid #c8a675;
}

.home-btn {
  background: linear-gradient(135deg, #c8a675 0%, #6a4c29 100%);
  color: #fff;
}

/* 支付确认弹窗 */
.confirm-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 10rpx 30rpx rgba(106, 76, 41, 0.2);
}

.confirm-title {
  font-size: 32rpx;
  color: #6a4c29;
  font-weight: bold;
  margin-bottom: 20rpx;
  font-family: "汉仪尚巍手书", "思源宋体", serif;
}

.confirm-amount {
  font-size: 50rpx;
  color: #6a4c29;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.confirm-method {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.confirm-tips {
  background-color: #f8f5ef;
  width: 100%;
  padding: 20rpx;
  border-radius: 10rpx;
  text-align: center;
  margin-bottom: 30rpx;
}

.confirm-tips text {
  font-size: 24rpx;
  color: #6a4c29;
}

.confirm-btns {
  display: flex;
  width: 100%;
  gap: 20rpx;
}

.confirm-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.cancel-btn {
  background-color: #f1e3c4;
  color: #6a4c29;
}

.proceed-btn {
  background: linear-gradient(135deg, #c8a675 0%, #6a4c29 100%);
  color: #fff;
}

/* 点击态效果 */
.payment-method-item:active {
  background-color: rgba(200, 166, 117, 0.1);
}

.pay-btn:active,
.success-btn:active,
.confirm-btn:active {
  opacity: 0.9;
  transform: scale(0.98);
}

/* 动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.success-content {
  animation: pulse 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.modal-mask {
  animation: fadeIn 0.3s ease-out;
}

/* 禁用按钮样式 */
.pay-btn[disabled] {
  opacity: 0.6;
  background: #ccc;
}
</style>
